﻿window['console']['log'] = function () {};
var dataOn = null;
var data = {
    t: "1559010885",
    r: "z2eG2RFma",
    z: "0E7E1911542C66EAA8081132D1CFDF5E"
};
$(function () {
    // 获取下拉
    var T = new Promise((resolve, reject) => {
        $.ajax({
            url: url + "admin/getCourseCategoryList",
            type: "post",
            dataType: "json",
            contentType: "application/x-www-form-urlencoded",
            data: data,
            success: function (res) {
                var data = res.data;
                var arr = [];
                if (res.code == 200) {
                    var arr = [];
                    for (var i = 0; i < res.data.length; i++) {
                        var item =
                            `
                                    <option value="${res.data[i].id}">${res.data[i].name}</option>
                                `
                        arr.push(item);
                        // arr3.push(res.data[i].id)
                        // arr4.push(res.data[i].name)
                    }
                    resolve(data)
                } else {
                    reject(error)
                }
                $('#courseIndexDown').append(arr);
                $("#courseDown").append(arr);
                renderSelect();
            }
        });
    })
    Promise.all([T, P]).then(values => {
        //  分页加载
        // 班级管理分页
        console.log(values);
        var aa = values[0];
        var cc = values[1];
        var cc1 = cc[1];
        cc1.forEach((item, index) => {
            aa.forEach((item1, index1) => {
                if (item1.id == item) {
                    $('.cname').eq(index).text(item1.name)
                }
            })
        })
        // for(var j = 0; j < cc1.length; j++) {
        //     for (var i = 0; i < aa.length; i++) {
        //         if (cc1[j] == aa[i].id) {
        //             // $('.cname').text(aa[i].name)
        //             $('.cname').eq(j).text(aa[i].name)
        //             console.log('成功');
        //         }
        //     }
        // }
        // 分页数据
        var laypage = layui.laypage;
        laypage.render({
            elem: "test1",
            count: cc1.total, //数据总数，从服务端得到
            limit: cc1.per_page,
            theme: "#2F72D5",
            jump: function (obj, first) {
                if (!first) {
                    courseList(obj.curr);
                }
            }
        });
    });
    $("button").attr("type", "button");
    $(document).on("click", '.addCourse', function () {
        let val = $(this).text()
        console.log(val);
        if (val == '编辑') {
            $('#addBtn').hide();
            $('#saveBtn').show();
            var id = $(this).parent().parent().children().eq(0).text();
            var name = $(this).parent().parent().children().eq(1).text();
            var classroomId = $(this).parent().parent().children().eq(7).children().eq(0).val();
            // var classroomId = $(this).parent().parent().children().eq(2).text();
            var classroomPrice = $(this).parent().parent().children().eq(3).text();
            var image = $(this).parent().next().children().eq(0).val();
            $('#courseDown').find('option').each(function () {
                let val = $(this).val()
                $(this).removeAttr('selected', 'selected')
                if (val == classroomId) {
                    console.log(23)
                    $(this).attr('selected', 'selected')
                    renderSelect()
                }
            });
            $('#className').val(name);
            // $('select[name="categoryId"]').append() ￥1000
            var newClassroomPrice = classroomPrice.substr(1, classroomPrice.length - 1);
            console.log(newClassroomPrice);
            $('#courseId').val(id)
            $('#classPrice').val(newClassroomPrice);
            $('#show').attr('src', url + image).show();
            $('.uploadPictures span').hide();

        } else if (val == '添加') {
            $('#addBtn').show();
            $('#saveBtn').hide();
        }
        // $(".classroomListContent").hide();
        $(".classroomListAdd").show();
        $(".courseListContent").hide();
        // document.getElementById("addform").reset();
        // console.log(12);
        $(".backBtn").click(function () {
            console.log(23);
            $(".courseListContent").show();
            $(".classroomListAdd").hide();
            $('.imgShow').hide();
            $('.uploadPictures span').show();
            document.getElementById("addform").reset();

        });
    });
    // 修改课程
    $('#saveBtn').click(function () {
        console.log('修改');
        var img = $("#input_file")[0].files[0];
        var reader = new FileReader();
        reader.readAsBinaryString(img);
        //reader.readAsDataURL(img);
        reader.addEventListener("loadend", function () {
            var formElement = document.getElementById("addform");
            var formData = new FormData(formElement);
            formData.append("t", "1559010885");
            formData.append("r", "z2eG2RFma");
            formData.append("z", "0E7E1911542C66EAA8081132D1CFDF5E");
            formData.append("categoryId", $('#courseDown').val());
            // for (var [a, b] of formData.entries()) {
            //     console.log(a, b);
            // }
            $.ajax({
                url: url + "admin/updateCourse",
                type: "POST",
                //contentType: "multipart/form-data",
                data: formData,
                processData: false,
                contentType: false,
                success: function (data, textStatus, jqXHR) {
                    // console.log(data);
                    $(".classroomListAdd").hide();
                    $(".AddSuccess").show();
                },
                error: function (jqXHR, textStatus, error) {
                    // console.log('error');
                }
            });
        });
    })

    // 获取下拉
    // $.ajax({
    //     url: url + "admin/getCourseCategoryList",
    //     type: "post",
    //     dataType: "json",
    //     contentType: "application/x-www-form-urlencoded",
    //     data: data,
    //     success: function (res) {
    //         var arr = [];
    //         for (var i = 0; i < res.data.length; i++) {
    //             var item =
    //                 `
    //                     <option value="${res.data[i].id}">${res.data[i].name}</option>
    //                 `
    //             arr.push(item);
    //         }
    //         $('#courseIndexDown').append(arr);
    //         $("#courseDown").append(arr);
    //         //   $('#addClassroomDropDown').append(arr)
    //         renderSelect();
    //     }
    // });

    // 提交修改表单
    $("#addBtn").click(function () {

        let a = $("#className").val();
        let b = $("#classPrice").val();
        let selectVal = $('select[name="selectVal"]').val();
        if (a == "") {
            layer.alert("请输入班级名称", {
                title: d,
                icon: 2
            });
        } else if (b == "") {
            layer.alert("请输入班级价格", {
                title: d,
                icon: 2
            });
        } else {
            var img = $("#input_file")[0].files[0];
            var d = "错误提示";
            var reader = new FileReader()
            reader.readAsBinaryString(img);
            //reader.readAsDataURL(img);
            reader.addEventListener("loadend", function () {
                var formElement = document.getElementById("addform");
                var formData = new FormData(formElement);
                formData.append('t', "1559010885");
                formData.append('r', "z2eG2RFma");
                formData.append('z', "0E7E1911542C66EAA8081132D1CFDF5E");
                formData.image = img;
                // console.log(typeof formData);
                // console.log(JSON.stringify(formData));
                $.ajax({
                    url: url + "admin/addCourse",
                    type: 'POST',
                    contentType: "multipart/form-data",
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function (data, textStatus, jqXHR) {
                        $('.classroomListAdd').hide();
                        $('.AddSuccess').show();
                    },
                    error: function (jqXHR, textStatus, error) {
                        console.log('error');
                    }
                })
            })
        }
    });
    // 添加成功后继续添加和返回
    $('.addClassBtn').click(function () {
        $('.AddSuccess').hide();
        $('.classroomListAdd').show();
        document.getElementById('addform').reset();
    });
    $('.returnClassBtn').click(function () {
        $('.AddSuccess').hide();
        $('.courseListContent').show();
        document.getElementById('addform').reset();
    });
    // 添加和获取的课时
    $(document).on('click', '.addClassHour', function () {
        // window.location.href = 'getclassHour.html'
        // var newData = Object.assign({}, data);
        var newId = $(this).parent().parent().children().eq(0).text();
        var newTitle = $(this).parent().parent().children().eq(1).text();
        window.location.href = 'getclassHour.html?id=' + newId + "&title=" + newTitle;
        // window.location.href = 'getclassHour.html?id=' + data[i].id + "&title=" + data[i].title + "&mediaUri=" + data[i].mediaUri + "&updatedTime=" + data[i].updatedTime + "&length=" + data[i].length;
    });
})
// ajax获取列表
var P = new Promise((resolve, reject) => {
    function courseList(page) {
        var newData = Object.assign({}, data);
        newData.page = page;
        $.ajax({
            url: url + "admin/getCourseList",
            type: "post",
            dataType: "json",
            contentType: "application/x-www-form-urlencoded",
            data: newData,
            success: function (response) {
                console.log(response);
                let dataOn = response.data;
                let data = response.data.data;
                let length = data.length;
                let arr = [];
                var arr2 = [];
                if (response.code == 200) {
                    for (i = 0; i < length; i++) {
                        // 日期转时间戳
                        function timestampToTime() {
                            let time = data[i].updatedTime;
                            var date = new Date(time * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
                            var Y = date.getFullYear() + '-';
                            var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
                            var D = date.getDate() + ' ';
                            return Y + M + D;
                        }
                        let changeColor = "price";
                        if (data[i].price == 0) {
                            changeColor = "zero";
                        }
                        var classRoomListContent = `
                                <tr>
                                    <td>${data[i].id}</td>
                                    <td>${data[i].title}</td>
                                    <td class="classification cname"></td>
                                    <td class="${changeColor}">${data[i].price == 0 ? "免费" : "￥" + data[i].price}</td>
                                    <td>${timestampToTime()}</td>
                                    <td class="courseOperation"><a class="addClassHour">添加课时</a><a class="removeClassBtn addCourse">编辑</a><a
                                    class="classroomOpen">删除</a></td>
                                    <td><input type="hidden" value="${data[i].largePicture}"></td>
                                  <td><input type="hidden" value="${data[i].categoryId}"></td>
                                </tr>
                            `
                        arr2.push(data[i].categoryId)
                        arr.push(classRoomListContent);
                    }
                    resolve([dataOn, arr2]);
                } else {
                    reject(error);
                }
                $(".courseListContent tbody").html(arr);
            }
        });
    }
    return courseList();
});


// 图片预览
function loadImg() {
    var reads = new FileReader();
    f = document.getElementById("input_file").files[0];
    reads.readAsDataURL(f);
    reads.onload = function (e) {
        $('.imgShow').show();
        $('.uploadPictures span').hide();
        document.getElementById("show").src = this.result;
    };
}

function renderSelect() {
    layui.use("form", function () {
        var form = layui.form;
        form.render();
        // console.log(2);
        //…
    });
}